package com.qiangqiang.service;

import com.qiangqiang.aop.annotation.CheckHasDormitory;
import com.qiangqiang.dto.BanDTO;
import com.qiangqiang.entity.Ban;
import com.qiangqiang.enums.RecordEnums;
import com.qiangqiang.exception.RecordException;
import com.qiangqiang.repository.BanRepository;
import com.qiangqiang.util.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by q on 2018/2/11.
 */
@Slf4j
@Service
public class BanService {

    @Autowired
    private BanRepository banRepository;

    /**
     * 增加一条违禁品记录
     *
     * @param banDTO
     */
    @CheckHasDormitory
    public void addBanRecord(String dId,String goods) {
        banRepository.insertBan(KeyUtil.getUniqueKey(), dId,goods);
    }

    /**
     * 分页查询所有记录
     *
     * @param page
     * @param size
     * @return
     */
    public Page<BanDTO> findAllBans(int page, int size) {
        PageRequest request = new PageRequest(page, size);
        Page<Ban> bans = banRepository.findAll(request);
        List<BanDTO> banDTOs = bans.getContent().stream()
                .map(e -> {
                    BanDTO banDTO = new BanDTO();
                    BeanUtils.copyProperties(e, banDTO);
                    return banDTO;
                }).collect(Collectors.toList());
        return new PageImpl(banDTOs);
    }

    /**
     * 根据宿舍号查询有没该条记录
     * @param dId
     * @return
     */
    public List<BanDTO> findByDId(String dId){
        List<Ban> bans=banRepository.queryAllByDId(dId);
        if(bans==null){
            throw new RecordException(RecordEnums.NOT_THIS_RECORD);
        }
        List<BanDTO> banDTOs=bans.stream()
                .map(e->{
                    BanDTO banDTO=new BanDTO();
                    BeanUtils.copyProperties(e,banDTO);
                    return banDTO;
                }).collect(Collectors.toList());
        return banDTOs;
    }
}
